<template>
  <section>
    <el-tabs v-model="activeName"
             @tab-click="handleClick">
      <el-tab-pane label="共用跟踪方式"
                   name="first">
        <div class="tips">
          <icon-svg icon-name="tishi1"
                    style="width:14px; height:14px;" />
          确定后，后台要进行每单绑定，页面显示跟踪信息需要一定时间，请耐心等待。
        </div>
        <el-form ref="ruleForm"
                 v-loading="boxLoading"
                 element-loading-text="拼命加载中"
                 element-loading-spinner="el-icon-loading"
                 class="form-style"
                 :model="ruleForm"
                 label-width="90px">
          <number-type v-if="!boxLoading"
                       :form-info="ruleForm"
                       :transport-type="transportType" />
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="不共用跟踪方式"
                   name="second">
        <div class="tips">
          <icon-svg icon-name="tishi1"
                    style="width:14px; height:14px;" />
          确定后，后台要进行每单绑定，页面显示跟踪信息需要一定时间，请耐心等待。
        </div>
        <el-row :gutter="20"
                class="form-style ">
          <el-col :span="21">
            <el-input v-model="text"
                      type="textarea"
                      show-word-limit
                      :placeholder="placeholder"
                      maxlength="1000"
                      :rows="4" />
          </el-col>
          <el-col :span="2">
            <el-button type="primary"
                       :loading="identifyLoading"
                       @click="handleIdentify">识别</el-button>
          </el-col>
        </el-row>
        <div class="content">
          <template v-for="(ele, index) in identifyContent">
            <el-row :key="index"
                    :gutter="20"
                    class="rowSty">
              <el-col :span="7">
                <span :title="ele.contractNo">{{ele.contractNo}}</span>
              </el-col>
              <el-col :span="4">
                <span>{{ele.trackTypeDesc}}</span>
              </el-col>
              <el-col :span="9"
                      class="flex-start">
                <span v-if="index">35160808<el-input v-model="ele.deviceCode"
                            placeholder="输入编号后七位"
                            style="width: 150px; margin-left: 5px" /></span>
                <span v-else>{{ele.deviceCode}}</span>
              </el-col>
              <el-col v-if="index"
                      :span="2">
                <span><el-button type="text"
                             @click="deleteRow(index)">删除</el-button></span>
              </el-col>
            </el-row>
          </template>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div v-if="!boxLoading"
         class="footer-button">
      <el-button type="default"
                 @click="handleCancel">取消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="handleSubmit('ruleForm')">{{
          loading ? "提交中 ..." : "确 定"
        }}</el-button>
    </div>
  </section>
</template>

<script>
import numberType from "@components/numberType/index";
import { dialogFulfill } from '@tablra/fulfill/executors/RequestExecutor'
import { mapState, mapActions } from "vuex";
import axios from 'axios';
export default {
  name: "TrackBatchBind",
  components: {
    numberType
  },
  inheritAttrs: true,
  props: {
    value: Object,
    query: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      code: '35160808',
      activeName: 'first',
      placeholder: '粘贴文本（合同编号 设备编号后七位）\n示例：\nzd-613001   6050300\nzd-613002   6050300',
      loading: false,
      identifyLoading: false,
      boxLoading: true,
      ruleForm: {
        trackType: 1,
        deviceCode: null
      },
      text: null,
      identifyContent: []
    }
  },
  computed: {
    ...mapState({
      batchBindId: (state) => state.batch.batchBindId,
    }),
    transportType () {
      return this.query?.transportType;
    },
    bindType () {
      return this.query?.bindType; // 1订单 2运单
    },
    orderIds () {
      return this.query?.orderIds || [];
    },
    orders () {
      return this.query?.orders || [];
    },
    waybillIds () {
      return this.query?.waybillIds || [];
    },
    waybills () {
      return this.query?.waybills || [];
    },
    url () {
      return this.activeName === 'first' ? this.query.batchUrl : this.query.url
    },
    method () {
      return this.bindType === "1" && this.activeName === "second" ? 'put' : 'post'
    },
    idCountExceeded () {
      return this.query?.selection?.length || 0
    },
    taskUrl () {
      return `/tenant/task/{id}`
    },
  },
  watch: {
    value: {
      handler (value) {
        this.$nextTick(() => {
          this.activeName = 'first'
          this.ruleForm.deviceCode = null
          this.ruleForm.trackType = 1
          this.boxLoading = false
        })
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions({
      setbatchBindId: "batch/setbatchBindId",
    }),
    handleClick (tab, event) {
      console.log(tab, event);
    },
    handleCancel () {
      this.$emit("cancel");
    },
    handleIdentify () {
      if (!this.text) {
        this.identifyContent = [];
        return;
      }
      this.identifyLoading = true;
      // 粘贴文本
      let rows = this.text.split("\n") || this.text.split(/\s+/);
      let textRows = [];
      rows.map(item => {
        let arr = item.split(/\s+/);
        if (arr.length === 1) {
          arr = item.split("\t")
        }
        if (arr[0] && arr[1]) {
          textRows.push({ contractNo: arr[0], deviceCode: arr[1] })
        }
        console.log("====textRows", textRows)
      })
      // 列表选中记录与粘贴文本匹配
      let arr = [{ contractNo: '合同编号', deviceCode: '跟踪方式', trackTypeDesc: '设备编号' }];
      let ids = [];
      if (this.bindType === "1") {
        // let newArr = this.orders.filter(v => textRows.some(o => o.contractNo === v.contractNo))
        textRows.filter(ele => {
          this.orders.forEach(function (item) {
            if (item.contractNo === ele.contractNo && !ids.includes(item.orderId)) {
              ids.push(item.orderId)
              arr.push({
                contractNo: item.contractNo,
                orderId: item.orderId,
                deviceCode: ele.deviceCode,
                trackTypeDesc: '电子回单',
                trackType: 1
              })
            }
          });
        })
      } else {
        textRows.filter(ele => {
          this.waybills.forEach(function (item) {
            if (item.contractNo === ele.contractNo && !ids.includes(item.waybillId)) {
              ids.push(item.waybillId)
              arr.push({
                contractNo: item.contractNo,
                waybillId: item.waybillId,
                deviceCode: ele.deviceCode,
                trackTypeDesc: '电子回单',
                trackType: 1
              })
            }
          });
        })
      }
      console.log("=====<identifyContent", arr)
      this.identifyContent = arr;
      this.identifyLoading = false;
    },
    deleteRow (index) {
      this.identifyContent.splice(index, 1);
    },
    handleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.activeName === 'first') {
            this.handleTrack({ ...this.ruleForm })
          } else {
            this.circulateTrack()
          }
        } else {
          return false;
        }
      });
    },
    // 共用
    handleTrack (params) {
      if (!params.deviceCode) {
        return this.$message.error(`${params.trackType === 1 ? '请选择电子回单！' : '请输入快递单号！'}`)
      }
      this.loading = true;
      let deviceCode = params.trackType === 1 ? (params.deviceCode ? `${this.code}${params.deviceCode}` : null) : params.deviceCode;
      if (this.bindType === "1") {
        this.actionDispatch({ orderIds: this.orderIds, name: "批量绑定", routes: [], trackNo: deviceCode, trackType: params.trackType });
      } else {
        this.actionDispatch({ waybillIds: this.waybillIds, name: "批量绑定", deviceDTO: { deviceCode, trackType: params.trackType, transports: [] } });
      }
    },
    // 不共用
    circulateTrack () {
      this.identifyContent.map(item => {
        if (item.orderId) {
          this.actionDispatch({ orderId: item.orderId, trackType: 1, trackNo: `${this.code}${item.deviceCode}`, routes: [] });
        }
        if (item.waybillId) {
          this.actionDispatch({ waybillId: item.waybillId, deviceDTO: { ...item, deviceCode: `${this.code}${item.deviceCode}`, transports: [] } });
        }
      })
    },
    async actionDispatch (params) {
      // let { code, data } = await axios[this.method](this.url, params)
      //   .catch(err => {
      //     this.loading = false;
      //   })
      const response = await this.wereBatchBind(params)
      this.loading = false;
      this.text = null;
      this.identifyContent = [];
      this.setbatchBindId(response)
      if (this.batchBindId) {
        this.handleIdCountExceeded(response);
      }
      // this.$emit("confirm");
      // this.$message({ type: "success", message: "操作成功" });
    },
    async wereBatchBind (params) {
      try {
        let response = await axios[this.method](this.url, params)
        if (response?.code === 0) {
          if (!response?.data) {
            this.loading = false
            this.$emit("confirm");
            this.$message({ type: "success", message: "操作成功" });
          }
          return response?.data;
        } else {
          this.loading = false
          this.$message({ type: "error", message: response?.message });
        }
      } catch {
        this.loading = false
      }
    },
    handleIdCountExceeded (data) {
      this.$emit("cancel");
      const component = {
        taskUrl: this.taskUrl,
        count: this.idCountExceeded,
        name: `批量绑定`,
        id: data || this.batchBindId
      };
      dialogFulfill.invoke(component);
    }
  }
}
</script>
<style scoped>
.form-style {
  min-height: 60px;
  margin-top: 10px;
  margin-bottom: 15px;
}
.footer-button {
  display: flex;
  justify-content: flex-end;
}
.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.rowSty {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 12px 5px;
}
.content {
  max-height: 360px;
  overflow-x: hidden;
}
.tips {
  font-size: 12px;
  color: var(--prev-color-primary);
  margin-bottom: 22px;
}
</style>
